package com.hhhn.wk.main.tab4;

import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.hhhn.wk.R;
import com.hhhn.wk.app.MyApplication;
import com.hhhn.wk.base.BaseActivity;
import com.hhhn.wk.entity.User;
import com.hhhn.wk.utils.AllPublic;
import com.hhhn.wk.utils.Constants;
import com.hhhn.wk.utils.SharePreferencesUser;
import com.hhhn.wk.utils.mi.AES;
import com.hhhn.wk.widget.customview.CircleImageView;
import com.hhhn.wk.widget.modifythehead.BitmapLoader;
import com.hhhn.wk.widget.modifythehead.FileHelper;
import com.hhhn.wk.widget.modifythehead.SelectDialog;
import com.hhhn.wk.widget.select_img.cache.CacheManager;
import com.hhhn.wk.widget.uploading_picture.FileUtils;
import com.imnjh.imagepicker.SImagePicker;
import com.imnjh.imagepicker.activity.PhotoPickerActivity;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.common.util.KeyValue;
import org.xutils.http.RequestParams;
import org.xutils.http.body.MultipartBody;
import org.xutils.x;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

/**
 * * * * * * * * * * * *
 * @author：文珂    ｡◕‿◕｡ *
 * Data：2018/1/2 0002    ｡◕‿◕｡ *
 * Function：      ｡◕‿◕｡ *
 * 个人资料
 * * * * * * * * * * * */
public class PersonalActivity extends BaseActivity {
    public static final String AVATAR_FILE_NAME = "avatar.png";
    public static final int REQUEST_CODE_AVATAR = 100;
    public static final int REQUEST_CODE_IMAGE = 101;
    private static final String TAG = "PersonalActivity";
//    private final int PHOTO_PICKED_FROM_CAMERA = 1; // 用来标识头像来自系统拍照
//    private final int PHOTO_PICKED_FROM_FILE = 2; // 用来标识从相册获取头像
//    private final int CROP_FROM_CAMERA = 3;
    private Uri uri=null;
    private String filePath = null;
    private TextView tv_title;//标题
    private TextView tv_upShopAddress;//商铺地址
    private TextView tv_upShopName;//商铺昵称
    private TextView tv_userNickName;//用户昵称
    private LinearLayout ll_upName;//修改昵称
    private CircleImageView iv_head;//用户头像
    private LinearLayout ll_head;//用户头像
    private Context context;
    private BaseActivity activity;
    private  User user=null;
    private String pathList_one="";
//    Uri zhengPath = null;
    @Override
    protected void setOnCreateContentView() {
        setContentView(R.layout.activity_personal);
        context=PersonalActivity.this;
        activity=this;
    }
    @Override
    protected void initView() {
        tv_title=findViewById(R.id.tv_title);
        tv_userNickName=findViewById(R.id.tv_userNickName);
        tv_upShopAddress=findViewById(R.id.tv_upShopAddress);
        tv_upShopName=findViewById(R.id.tv_upShopName);
        ll_upName=findViewById(R.id.ll_upName);
        iv_head=findViewById(R.id.iv_head);
        ll_head=findViewById(R.id.ll_head);
    }
    @Override
    protected void initData() {
        tv_title.setText("个人资料");
        user = (User) SharePreferencesUser.getBean(activity, Constants.USER);
        tv_upShopName.setText(user.getCompany_name());
        tv_upShopAddress.setText(user.getCompany_address());
        tv_userNickName.setText(user.getUserNickname());
        AllPublic.showImg(context,user.getUserImg(),iv_head);
    }
    @Override
    protected void initClick() {
//        ll_upShopAddress.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
//                Intent intent=new Intent(context,UpShopAddressActivity.class);
//
//                startActivity(intent);
//            }
//        });
//        ll_upShopName.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
//                Intent intent=new Intent(context,UpShopNameActivity.class);
//
//                startActivity(intent);
//            }
//        });
        ll_upName.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent=new Intent(context,UpNameActivity.class);
                startActivityForResult(intent,4);
            }
        });
        //修改头像
        ll_head.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
//                selectPhoto();
                SImagePicker
                        .from(activity)
                        .pickMode(SImagePicker.MODE_AVATAR)
                        .showCamera(true)
                        .cropFilePath(
                                CacheManager.getInstance().getImageInnerCache()
                                        .getAbsolutePath(AVATAR_FILE_NAME))
                        .forResult(REQUEST_CODE_AVATAR);
            }
        });
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            final ArrayList<String> pathList =
                    data.getStringArrayListExtra(PhotoPickerActivity.EXTRA_RESULT_SELECTION);
            final boolean original =
                    data.getBooleanExtra(PhotoPickerActivity.EXTRA_RESULT_ORIGINAL, false);
            Glide.with(MyApplication.getAppContext()).load(pathList.get(0)).skipMemoryCache(true)
                    .diskCacheStrategy(DiskCacheStrategy.NONE)
                    .dontAnimate().into(iv_head);
            Log.e(TAG, "新: "+pathList.get(0));
            pathList_one=pathList.get(0);
            goOK1(pathList.get(0));
        }
        if(requestCode==4&&resultCode==1){
            tv_userNickName.setText(activity.getUser().getUserNickname());
            sendBR();
        }
    }
    public void sendBR(){
        LogWk("修改成功发送广播");
        Intent intent = new Intent();
        intent.setAction(Constants.MBroadcastReceiver);
        sendBroadcast(intent);
    }
//    private void selectPhoto() {
//        List<String> list = new ArrayList<>();
//        list.add("拍照");
//        list.add("相册");
//        showDialog(new SelectDialog.SelectDialogListener() {
//            @Override
//            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//                switch (position){
//                    case 0:
//                        getIconFromCamera();
//                        break;
//                    case 1:
//                        getIconFromPhoto(); // 从系统相册获取
//                        break;
//                    default:
//                        break;
//                }
//            }
//        },list);
//    }
    //相册
//    private void getIconFromPhoto(){
//        if (FileHelper.isSdCardExist()) {
//            Intent intent;
//            if (Build.VERSION.SDK_INT < 19) {
//                intent = new Intent(Intent.ACTION_GET_CONTENT);
//                intent.setType("image/*");
//            } else {
//                intent = new Intent(Intent.ACTION_PICK,
//                        android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
//            }
//            startActivityForResult(intent, PHOTO_PICKED_FROM_FILE);
//        } else {
//            Toast.makeText(this, "暂无外部存储器",
//                    Toast.LENGTH_SHORT).show();
//        }
        // 激活系统图库，选择一张图片
//        Intent intent = new Intent(Intent.ACTION_PICK);
//        intent.setType("image/*");
//        // 开启一个带有返回值的Activity，请求码为PHOTO_REQUEST_GALLERY
//        startActivityForResult(intent, PHOTO_PICKED_FROM_FILE);
//    }
//    //相机
//    private void getIconFromCamera() {
//        if (FileHelper.isSdCardExist()) {
//            filePath = FileHelper.createAvatarPath(null);
//            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
//            intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(filePath)));
//            try {
//                startActivityForResult(intent, PHOTO_PICKED_FROM_CAMERA);
//            } catch (ActivityNotFoundException anf) {
//                Toast.makeText(context, "dddd",
//                        Toast.LENGTH_SHORT).show();
//            }
//        } else {
//            Toast.makeText(context, "eee",
//                    Toast.LENGTH_SHORT).show();
//        }
//    }
//    private SelectDialog showDialog(SelectDialog.SelectDialogListener listener, List<String> list){
//        SelectDialog dialog = new SelectDialog(this,
//                R.style.transparentFrameWindowStyle,listener,list);
//        dialog.show();
//        return dialog;
//    }

//    /**
//     * 裁剪
//     * @param uri
//     */
//    private void crop(Uri uri) {
////        　　　　　//看到有人问裁剪的路径
////        　　　　// 获取系统时间 然后将裁剪后的图片保存至指定的文件夹
//        SimpleDateFormat sDateFormat = new SimpleDateFormat("yyyyMMddhhmmss");
//        String address = sDateFormat.format(new java.util.Date());
//       String imagePath = address + ".JPEG";
//        Uri imageUri = Uri.fromFile(new File(FileUtils.SDPATH + imagePath));
//        File file = new File(FileUtils.SDPATH);
//        if (!file.exists()) {
//            Log.d("@@", "photo: 没有文件夹");
//            file.mkdirs();
//        } else {
//            Log.d("@@", "photo: 有文件夹");
//        }
//        // 裁剪图片意图
//        Intent intent = new Intent("com.android.camera.action.CROP");
//        intent.setDataAndType(uri, "image/*");
//        intent.putExtra("crop", "true");
//        // 裁剪框的比例，1：1
//        intent.putExtra("aspectX", 1);
//        intent.putExtra("aspectY", 1);
//        // 裁剪后输出图片的尺寸大小
//        intent.putExtra("outputX", 250);
//        intent.putExtra("outputY", 250);
//        intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);//输出路径
//        intent.putExtra("outputFormat", "JPEG");// 图片格式
//        intent.putExtra("noFaceDetection", true);// 取消人脸识别
//        intent.putExtra("return-data", true);
//        // 开启一个带有返回值的Activity，请求码为PHOTO_REQUEST_CUT
//        startActivityForResult(intent, CROP_FROM_CAMERA);
//    }

//    /**
//     * 上传头像
//     */
//
//    private void uoHeadImg(){
//        //上传这个路径
//        String realFilePath = FileUtils.getRealFilePath(context, uri);
//        LogWk(realFilePath);
//
//        goOK1(realFilePath);
//    }
    /**
     * 提交1图片
     */
    private void goOK1(String realFilePath) {
        showLoad();
        RequestParams params = new RequestParams(Constants.HTTPUPIMG);
        params.addHeader("Content-Type", "application/x-www-form-urlencoded");
        List<KeyValue> list = new ArrayList<>();
        //请求参数
        if (realFilePath!=null && !realFilePath.equals("")){
            list.add(new KeyValue("file_data", new File(realFilePath)));
        }
        MultipartBody body = new MultipartBody(list, "UTF-8");
        params.setRequestBody(body);
        Log.d(TAG, "params: "+params);
        //请求
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override  //成功
            public void onSuccess(String result) {
                Log.d("提交1图片", result);
                try {
                    JSONObject jsonObject= new JSONObject(result);
                    int reason = jsonObject.getInt("code");
                    if (reason==0) {
                        String data = jsonObject.getString("data");
                        goOK(data);
                    }else {
                        toastWk(jsonObject.getString(getResources().getString(R.string.errMsg)));
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Log.d("提交1图片-第二个", ex + "");
                ex.printStackTrace();
            }
            @Override
            public void onCancelled(CancelledException cex) {
                Log.d("提交1图片-第三个", cex + "");
            }
            @Override
            public void onFinished() {
                Log.d("提交1图片-第四个", "onFinished");
            }
        });

    }
    /**
     * 提交2
     */
    private void goOK(final String data) {
        RequestParams params = AllPublic.getParamsAccount(activity, "/changeHead", false);
        try {
            JSONObject person=new JSONObject();
            person.put("id",user.getUid());
            person.put("headPortrait",data);
            AES aes = AllPublic.jsonDesPackaging(person);
            params.addParameter("data",aes.getData());
            params.addParameter("key",aes.getKey());
        } catch (JSONException e) {
            e.printStackTrace();
        }


        //请求
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override  //成功
            public void onSuccess(String decode) {
                String result = AllPublic.jsonDesDecode(decode);//解密
                try {
                    JSONObject jsonObject= new JSONObject(result);
                    String reason = jsonObject.getString("code");
                    if (reason.equals("0")) {//成功
//                    Glide.with(context).
//                            load(zhengPath).
//                            into(iv_head);
                        Glide.with(MyApplication.getAppContext()).load(pathList_one).skipMemoryCache(true)
                                .diskCacheStrategy(DiskCacheStrategy.NONE)
                                .dontAnimate().into(iv_head);
                        user.setUserImg(data);
                        SharePreferencesUser.putBean(activity,Constants.USER, user);
                        sendBR();
                        toastWk("修改成功");
                    }else {
                        toastWk(jsonObject.getString(getResources().getString(R.string.errMsg)));
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    dismissLoad();
                }
                dismissLoad();
            }
            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Log.d("提交-第二个", ex + "");
                ex.printStackTrace();
                dismissLoad();
            }
            @Override
            public void onCancelled(CancelledException cex) {
                Log.d("提交-第三个", cex + "");
                dismissLoad();
            }
            @Override
            public void onFinished() {
                Log.d("提交-第四个", "onFinished");
                dismissLoad();
            }
        });

    }



}
